<template>
	<view class="page-container">
		<!-- 状态切换栏 -->
		<view class="status-tabs" v-if="statusList.length > 0">
			<scroll-view class="tab-scroll" scroll-x="true" show-scrollbar="false" scroll-with-animation>
				<view class="tab-content">
					<view v-for="(status, index) in statusList" :key="index" class="tab-item"
						:class="{'tab-active': currentStatus === status.value}" @click="switchStatus(status.value)">
						<text class="tab-text">{{status.label}}</text>
						<text class="tab-count"
							v-if="status.count > 0">{{status.count > 99 ? '99+' : status.count}}</text>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 订单列表 -->
		<view v-if="filteredOrders.length > 0" class="order-list">
			<view v-for="(order, index) in filteredOrders" :key="index" class="order-container"
				@click="onOrderItemClicked(order.orderNo)">
				<view class="order-header">
					<text class="order-no">订单号: {{order.orderNo}}</text>
					<text class="status-badge" :class="getStatusClass(order.orderStatus)">{{order.orderStatus}}</text>
				</view>

				<view class="product-row">
					<image :src="order.productCover" mode="aspectFit" class="product-cover"></image>
					<view class="product-info">
						<text class="product-name">{{order.productName}}</text>
						<view class="product-spec" v-if="order.specification">规格: {{order.specification}}</view>
						<view class="price-row">
							<text class="quantity">x{{order.quantity || 1}}</text>
							<text class="pay-amount">¥{{order.payAmount}}</text>
						</view>
					</view>
				</view>

				<view class="order-footer">
					<text class="order-time">{{formatTime(order.createTime)}}</text>
					<view class="order-actions">
						<button class="btn secondary" v-if="order.orderStatus === '待付款'"
							@click.stop="cancelOrder(order.orderNo)">
							取消订单
						</button>
						<button class="btn primary" v-if="order.orderStatus === '待付款'"
							@click.stop="payOrder(order.orderNo)">
							立即支付
						</button>
						<button class="btn secondary" v-if="order.orderStatus === '待收货'"
							@click.stop="confirmReceipt(order.orderNo)">
							确认收货
						</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view v-else class="empty-state">
			<image src="/static/empty-order.png" class="empty-image"></image>
			<text class="empty-text">{{getEmptyText()}}</text>
		</view>
	</view>
</template>

<script>
	import Order from '../../models/order'

	export default {
		onLoad() {
			this.fetchOrderList()
		},
		data() {
			return {
				allOrders: [],
				filteredOrders: [],
				currentStatus: 'all',
				statusList: []
			}
		},
		methods: {
			onOrderItemClicked(orderNo) {
				uni.navigateTo({
					url: `/pages/order/order?orderNo=${orderNo}`
				})
			},

			switchStatus(status) {
				this.currentStatus = status
				this.filterOrders()
			},

			getStatusClass(status) {
				const statusMap = {
					'待付款': 'pending',
					'待发货': 'toship',
					'待收货': 'shipped',
					'已完成': 'completed',
					'已取消': 'cancelled',
					'退款中': 'refund',
					'已退款': 'refunded'
				}
				return statusMap[status] || 'default'
			},

			formatTime(time) {
				if (!time) return ''
				if (typeof time === 'number') {
					const date = new Date(time)
					const now = new Date()
					const diff = now - date
					const days = Math.floor(diff / (1000 * 60 * 60 * 24))

					if (days === 0) {
						return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
					} else if (days === 1) {
						return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
					} else if (days < 7) {
						return `${days}天前`
					} else {
						return `${date.getMonth() + 1}月${date.getDate()}日`
					}
				}
				return time
			},

			generateStatusList(orders) {
				const statusCount = {}
				orders.forEach(order => {
					statusCount[order.orderStatus] = (statusCount[order.orderStatus] || 0) + 1
				})

				const statusList = [{
					label: '全部',
					value: 'all',
					count: orders.length
				}]

				Object.keys(statusCount).forEach(status => {
					statusList.push({
						label: status,
						value: status,
						count: statusCount[status]
					})
				})

				this.statusList = statusList
			},

			filterOrders() {
				if (this.currentStatus === 'all') {
					this.filteredOrders = [...this.allOrders]
				} else {
					this.filteredOrders = this.allOrders.filter(order => order.orderStatus === this.currentStatus)
				}
			},

			parseFromJsonArray(jsonArray) {
				let orders = []
				for (let i = 0; i < jsonArray.length; i++) {
					let jsonObject = jsonArray[i]
					let order = new Order(
						jsonObject.orderNo,
						jsonObject.createTime,
						jsonObject.productName,
						`${this.constant.BASE_URL}${jsonObject.productCover}`,
						jsonObject.orderStatus,
						jsonObject.payAmount
					)

					order.quantity = jsonObject.quantity || 1
					order.specification = jsonObject.specification

					orders.push(order)
				}

				orders.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
				return orders
			},

			getEmptyText() {
				if (this.currentStatus === 'all') return '暂无订单'
				const currentStatusItem = this.statusList.find(item => item.value === this.currentStatus)
				return `暂无${currentStatusItem?.label || ''}订单`
			},

			cancelOrder(orderNo) {
				uni.showModal({
					title: '确认取消',
					content: '确定要取消这个订单吗？',
					success: (res) => {
						if (res.confirm) {
							uni.showToast({
								title: '订单已取消',
								icon: 'success'
							})
							this.fetchOrderList()
						}
					}
				})
			},

			payOrder(orderNo) {
				uni.showToast({
					title: '跳转支付...',
					icon: 'none'
				})
			},

			confirmReceipt(orderNo) {
				uni.showModal({
					title: '确认收货',
					content: '请确认您已收到商品',
					success: (res) => {
						if (res.confirm) {
							uni.showToast({
								title: '确认收货成功',
								icon: 'success'
							})
							this.fetchOrderList()
						}
					}
				})
			},

			fetchOrderList() {
				uni.showLoading({
					title: '加载中...'
				})

				uni.request({
					url: `${this.constant.BASE_URL}/api/order/list`,
					method: 'GET',
					header: {
						'Authorization': this.loginManager.getToken()
					},
					success: (res) => {
						uni.hideLoading()
						if (res.data.code == 200) {
							this.allOrders = this.parseFromJsonArray(res.data.rows)
							this.generateStatusList(this.allOrders)
							this.filterOrders()
						} else {
							uni.showToast({
								title: res.data.message || '加载失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						uni.hideLoading()
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						})
					}
				})
			}
		}
	}
</script>

<style>
	.page-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}

	.status-tabs {
		background: #fff;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
		position: sticky;
		top: 0;
		z-index: 999;
		height: 100rpx;
	}

	.tab-scroll {
		white-space: nowrap;
		width: 100%;
		height: 115%;
	}

	.tab-content {
		display: inline-flex;
		align-items: center;
		height: 100%;
		padding: 0 20rpx;
	}

	.tab-item {
		display: inline-flex;
		align-items: center;
		padding: 16rpx 32rpx;
		margin: 0 10rpx;
		border-radius: 40rpx;
		background: #f8f8f8;
		position: relative;
		flex-shrink: 0;
		height: 60rpx;
	}

	.tab-active {
		background: #007AFF;
	}

	.tab-text {
		font-size: 28rpx;
		color: #333;
	}

	.tab-active .tab-text {
		color: #fff;
	}

	.tab-count {
		position: absolute;
		top: -8rpx;
		right: -8rpx;
		background: #ff3b30;
		color: white;
		border-radius: 20rpx;
		padding: 4rpx 10rpx;
		font-size: 20rpx;
		min-width: 24rpx;
		text-align: center;
		transform: scale(0.9);
	}

	.order-list {
		flex: 1;
		padding: 20rpx;
	}

	.order-container {
		background: #fff;
		margin-bottom: 20rpx;
		padding: 30rpx;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.04);
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.order-no {
		color: #999;
		font-size: 24rpx;
	}

	.product-row {
		display: flex;
		margin-bottom: 20rpx;
	}

	.product-cover {
		width: 160rpx;
		height: 160rpx;
		border-radius: 10rpx;
		flex-shrink: 0;
	}

	.product-info {
		flex: 1;
		margin-left: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.product-name {
		color: #333;
		font-size: 32rpx;
		line-height: 1.4;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.product-spec {
		color: #999;
		font-size: 24rpx;
		margin: 8rpx 0;
	}

	.price-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.quantity {
		color: #999;
		font-size: 28rpx;
	}

	.pay-amount {
		color: #ff5000;
		font-weight: bold;
		font-size: 36rpx;
	}

	.order-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.order-time {
		color: #999;
		font-size: 24rpx;
	}

	.order-actions {
		display: flex;
		gap: 16rpx;
	}

	.btn {
		padding: 12rpx 24rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		border: 1rpx solid;
		background: white;
	}

	.primary {
		background: #007AFF;
		color: white;
		border-color: #007AFF;
	}

	.secondary {
		color: #666;
		border-color: #ddd;
	}

	.status-badge {
		padding: 8rpx 20rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		font-weight: 500;
	}

	.pending {
		background: #fff2e8;
		color: #ff6a00;
		border: 1rpx solid #ffd8bf;
	}

	.toship {
		background: #e6f7ff;
		color: #1890ff;
		border: 1rpx solid #bae7ff;
	}

	.shipped {
		background: #f6ffed;
		color: #52c41a;
		border: 1rpx solid #b7eb8f;
	}

	.completed {
		background: #f9f0ff;
		color: #722ed1;
		border: 1rpx solid #d3adf7;
	}

	.cancelled {
		background: #f5f5f5;
		color: #8c8c8c;
		border: 1rpx solid #d9d9d9;
	}

	.refund {
		background: #fff7e6;
		color: #fa8c16;
		border: 1rpx solid #ffd591;
	}

	.refunded {
		background: #f6ffed;
		color: #52c41a;
		border: 1rpx solid #b7eb8f;
	}

	.default {
		background: #f5f5f5;
		color: #8c8c8c;
		border: 1rpx solid #d9d9d9;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 60vh;
	}

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 40rpx;
		opacity: 0.6;
	}

	.empty-text {
		color: #999;
		font-size: 28rpx;
	}
</style>